package com.yxhl.zoume.domain.interactor.base;

import com.yxhl.zoume.data.http.rest.param.base.RequestParamImpl;
import com.yxhl.zoume.domain.DomainConstants;
import com.yxhl.zoume.domain.interactor.ZMSubscriber;

import javax.inject.Named;

import rx.Observable;
import rx.Scheduler;
import rx.Subscription;
import rx.subscriptions.Subscriptions;

/**
 * 业务基类
 * JSON数据格式适用
 * <p>
 * Created by Xboy on 16/3/16.
 */
public abstract class UseCase<T> {
    // the uiThread to perform observation actions on
    protected final Scheduler uiThread;
    // the executorThread to perform subscription actions on
    protected final Scheduler executorThread;
    private Subscription subscription = Subscriptions.empty();


    public UseCase(@Named(DomainConstants.UI_THREAD) Scheduler uiThread,
                   @Named(DomainConstants.EXECUTOR_THREAD) Scheduler executorThread) {
        this.uiThread = uiThread;
        this.executorThread = executorThread;
    }

    /**
     * Builds an {@link rx.Observable} which will be used when executing the current {@link UseCase}.
     *
     * @return
     */
    protected abstract Observable<T> buildObservable(RequestParamImpl param);

    /**
     * Executes the current use case.
     *
     * @return
     */
    public void execute(RequestParamImpl param, ZMSubscriber<T> zmSubscriber) {
        subscription = buildObservable(param).subscribe(zmSubscriber);
    }

    public void unsubscribe() {
        if (!subscription.isUnsubscribed())
            subscription.unsubscribe();
    }
}
